package com.accloud.utils;

import android.net.http.X509TrustManagerExtensions;
import android.os.Build;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

public class SecurityUtils {
    private static final String AUTH_TYPE = "RSA";

    public static void validatePinning(HttpsURLConnection connection) throws SSLException, GeneralSecurityException {
        X509TrustManagerExtensions trustManagerExt = new X509TrustManagerExtensions(getX509TrustManager());
        Certificate[] serverCerts = connection.getServerCertificates();
        List<X509Certificate> trustedChain = trustManagerExt.checkServerTrusted((X509Certificate[]) Arrays.copyOf(serverCerts, serverCerts.length, X509Certificate[].class), AUTH_TYPE, connection.getURL().getHost());
        if (trustedChain.size() == 0) {
            throw new SSLPeerUnverifiedException("Ordered X509Certificates chain not found");
        } else if (Build.VERSION.SDK_INT >= 21) {
            for (X509Certificate certificate : trustedChain) {
                if (trustManagerExt.isUserAddedCertificate(certificate)) {
                    throw new SSLPeerUnverifiedException("User added X509Certificate found in chain");
                }
            }
        }
    }

    private static X509TrustManager getX509TrustManager() throws NoSuchAlgorithmException, KeyStoreException {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        for (TrustManager trustManager : trustManagers) {
            if (trustManager instanceof X509TrustManager) {
                return (X509TrustManager) trustManager;
            }
        }
        return null;
    }
}
